package com.jp.knowledge.service;

import android.content.SharedPreferences;
import android.os.Environment;

import com.google.gson.JsonObject;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.VersionBean;
import com.jp.knowledge.util.ResultSubscriber;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import okhttp3.ResponseBody;
import rx.Subscriber;
import rx.functions.Func1;

/**
 * Created by 528787067@qq.com on 2017/3/1.
 */

public class CheckVersionService extends BaseService implements ResultSubscriber.OnResultListener {

    private static String H5_VERSION_DATA = "H5VersionData";
    private static String VERSION = "version";
    private static String LATEST = "latest";

    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private VersionBean versionBean;
    private String localH5Dir;

    @Override
    public void onCreate() {
        super.onCreate();
        init();
        checkH5Version();
    }

    private void init(){
        sp = getSharedPreferences(H5_VERSION_DATA, MODE_PRIVATE);
        editor = sp.edit();
//        try {
//            localH5Dir = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) + "/jp580/";
//        } catch (Exception e){
            localH5Dir = getCacheDir() + "/jp580/";
//        }
    }

    /* 获取 H5 离线包的最新版本 */
    private void checkH5Version(){
        JsonObject param = new JsonObject();
        param.addProperty("token", HttpHelper.token);
        param.addProperty("version", sp.getLong(LATEST, 0));
        HttpHelper.getInstance(this).checkH5Version(param, 0x01, CheckVersionService.this);
    }

    /* 下载 H5 离线包 */
    private boolean downloadH5Package(){
        if(versionBean == null || versionBean.getVersion() == null)
            return false;
//        ToasUtil.toast(this, "发现新的离线包，后台更新中...");
        HttpHelper.getInstance(this).downloadFile(versionBean.getVersion(), new Func1<ResponseBody, String>(){
            @Override
            public String call(ResponseBody body) {
//                return saveH5Package(body);
                return unZip(body);
            }
        }, new Subscriber<String>(){
            @Override
            public void onCompleted() {
                CheckVersionService.this.stopSelf();
            }
            @Override
            public void onError(Throwable e) {
//                ToasUtil.toast(CheckVersionService.this, "离线包更新失败");
                onCompleted();
            }
            @Override
            public void onNext(String filePath) {
                if(filePath == null){
                    onError(new Throwable());
                    return;
                }
//                ToasUtil.toast(CheckVersionService.this, "离线包更新成功");
                saveVersionBean();
            }
        });
        return true;
    }

    /* 保存离线包到本地 */
    private String saveH5Package(ResponseBody body) {
        String path = localH5Dir + "../";
        if(versionBean != null)
            path += versionBean.getLatest();
        else
            path += "0";
        File file = new File(path);
        File parent = file.getParentFile();
        if (!parent.exists())
            parent.mkdirs();
        InputStream input = body.byteStream();
        try {
            OutputStream out = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = input.read(buf)) != -1)
                out.write(buf, 0, len);
            out.close();
            input.close();
        } catch (Exception e) {
            return null;
        }
        return path;
    }

    /* 解压 ZIP */
    private String unZip(ResponseBody body) {
        String strEntry;
        int buffer = 1024;
        try {
            BufferedOutputStream dest;
            ZipEntry entry;
            ZipInputStream zis = new ZipInputStream(new BufferedInputStream(body.byteStream()));
            while ((entry = zis.getNextEntry()) != null) {
                int count;
                byte data[] = new byte[buffer];
                strEntry = entry.getName();
                File entryFile = new File(localH5Dir + strEntry);
                File entryDir = new File(entryFile.getParent());
                if (!entryDir.exists())
                    entryDir.mkdirs();
                FileOutputStream fos = new FileOutputStream(entryFile);
                dest = new BufferedOutputStream(fos, buffer);
                while ((count = zis.read(data, 0, buffer)) != -1)
                    dest.write(data, 0, count);
                dest.flush();
                dest.close();
            }
            zis.close();
        } catch (Exception e) {
            return null;
        }
        return localH5Dir;
    }

    /* 保存版本信息 */
    private boolean saveVersionBean(){
        if(versionBean == null)
            return false;
        editor.putString(VERSION, versionBean.getVersion());
        editor.putLong(LATEST, versionBean.getLatest());
        editor.commit();
        return true;
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {}
    @Override
    public void onError(int requestType) {
        stopSelf();
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0) {
            onError(requestType);
            return;
        }
        versionBean = data.getEntity(VersionBean.class);
        if(sp.getLong(LATEST, 0) >= versionBean.getLatest())
            stopSelf();
        else
            downloadH5Package();
    }
}
